<?php
declare(strict_types=1);

namespace Service\UserService;
use Service\BaseService;
use Service\Code\Normal;
use Service\MessageService\SmsService;
use Service\PayService\Payer\Wxmnapp;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\Member;
use App\Model\BbcModel\ShoppingGuide;
use App\Model\BbcModel\MemberInfo;
use App\Model\BbcModel\MemberGuideLog;

/**
 * TO C/B 用户中心
 * @author chenshubo
 */
class UserService extends BaseService
{
    /**
     * 登录
     * @param int $cid
     * @param int $mnid
     * @param int $mn_sid
     * @param string $client
     * @param array $body
     * @return mixed
     */
    public function login(int $cid,int $mnid,int $mn_sid,string $client,array $param = [] )
    {
        if( empty($param['mobile']) ) {
            return Normal::returnCode(Normal::FAIL,"手机号码不能为空");
        }
        
        $mobile = $param['mobile'];
        if( !checkUserMobileReg($mobile) ) {
            return Normal::returnCode(Normal::FAIL,"手机号码格式不正确，请重新输入");
        }
        
        $env = isDebugMode();
        if( !$env && !empty($param['code']) )
        {
            //验证短信
            $result = SmsService::instance()->checkSmsCode($cid,$param['mobile'],$param['code']);
            if( $result['code'] != Normal::SUC ) {
                return $result;
            }
        }
        
        //验证微信参数
        if( empty($param['js_code']) && empty($param['openid']) ) {
            return Normal::returnCode(Normal::FAIL,"缺少参数js_code或者openid");
        }
        
        //获取微信小程序openid
        if( !empty($param['js_code']) && empty($param['openid']) )
        {
            $result_openinfo = Wxmnapp::instance()->codeToSession($cid, $mn_sid, $mnid, $param['js_code']);
            if( $result_openinfo['code'] != Normal::SUC ) {
                return $result_openinfo;
            }
            $param['openid']     = $result_openinfo['data']['openid'];
            $param['unionid']    = $result_openinfo['data']['unionid']??'';
        }
        
        $param['openid']     = $result_openinfo['data']['openid'] = '445s4df4as5f64as5d4fas4df';
        $param['unionid']    = $result_openinfo['data']['unionid']??'566478978979879879';
        
        //需要绑定的店铺ID
        $bind_mn_sid = $mn_sid;
        
        //查询店铺是否是共享用户
        if( $mnid == TO_B_MNID_TYPE ){
            $member = Member::instance()->info(['account' => $param['mobile'],'mn_sid'=>0,'cid'=>$cid]);
        }
        elseif ( $mnid == TO_C_MNID_TYPE ) 
        {
            $usedMember = [];
            $storeInfo = Mnuser::instance()->info(['id'=>$mn_sid,'status'=>1,'new_store'=>1]);
            if ( empty($storeInfo) ) {
                return Normal::returnCode(Normal::FAIL,"店铺不存在");
            }
            
            if( $storeInfo['member_share'] == 2 )
            {
                //非共享
                if( empty($usedMember) ) 
                {
                    $member = Member::instance()->info(['account' => $param['mobile'],'mn_sid'=>$mn_sid]);
                }
                else
                {
                    $member = $usedMember;
                }
            }
            else
            {
                //共享
                $mn_sids        = Mnuser::instance()->where(['member_share'=>1,'status'=>1,'new_store'=>1,'pid'=>$cid])->column('id');
                $member         = Member::instance()->info([['account' ,'=', $param['mobile']],['mn_sid','in',$mn_sids]]);
                $bind_mn_sid    = 0;
            }
        }
        
        //会员ID
        $mid = !empty($member['mid']) ? $member['mid'] : null;
        $param['nickname']  = "用户昵称".$param['mobile'];
        
        Member::instance()->startTrans();
        try
        {
            if (empty($mid)) 
            {
                //=0 就是to B 用户
                $account['mn_sid'] = $mnid == TO_C_MNID_TYPE ? $mn_sid : 0;
                $result_add_member = MemberService::instance()->addUser($cid, $mn_sid,$client,$param);
                if ($result_add_member['code'] != Normal::SUC) {
                    Member::instance()->rollback();
                    return $result_add_member;
                }
                                
                $mid    = $result_add_member['data']['member_id'];
                $member = Member::instance()->info(['mid' => $mid]);
            }
            else
            {
                $account = MemberInfo::instance()->info(['mid'=>$mid]);
                if( !empty($param['guide_code']) )
                {
                    $where_guide = [
                        'code'      => trim($param['guide_code']),
                        'mn_sid'    => $mn_sid,
                        'cid'       => $cid,
                        'status'    => 1
                    ];
                    $info = ShoppingGuide::instance()->info($where_guide);
                    if( $info ) {
                        
                        $guide_id = $info['id'];
                        MemberInfo::instance()->where('mid',$mid)->update([
                            'guide_now' => $guide_id,
                            'guide_md'  => time()
                        ]);
                        MemberGuideLog::instance()->add([
                            'mid'       => $mid,
                            'guide_id'  => $guide_id,
                            'cd'        => time()
                        ]);
                    }
                }
                
                $account['img']     = $account['avatar'];
                $account['account'] = $member['account'];
                
                //更新所属店铺
                if( $member['mn_sid'] == 0 && $mn_sid > 0 && $mnid == TO_C_MNID_TYPE ) 
                {
                    Member::instance()->where('mid',$member['mid'])->update(['mn_sid'=>$mn_sid]);
                }
            }
            
            //更新最后登录时间
            Member::instance()->where('mid',$mid)->update([
                'last_login_time'   => time()
            ]);
            
            //绑定自动登录
            $param['auto_login'] = !empty($param['auto_login']) ? $param['auto_login'] : false;
            $result_auto_login = UserAuthLoginService::instance()->bindAutoLogin($client,$cid,$mid,$mnid,$bind_mn_sid,$param);
            if ( $result_auto_login['code'] != Normal::SUC ) {
                Member::instance()->rollback();
                return $result_auto_login;
            }
            
            
            Member::instance()->commit();
            return $result_auto_login;
        }
        catch ( \Throwable $e)
        {
            Member::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,"初始化登录失败【{$e->getMessage()}】",[
                'errorMsg'      => $e->getMessage(),
                'errorLine'     => $e->getLine(),
                'errorFile'     => $e->getFile(),
            ]);
        }
    }
}